package com.qdsg.ysg.doctor.util;

import android.util.Log;

import com.qdsg.ysg.doctor.base.BaseApplication;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.response.BaseStringResponse;
import com.rest.response.PicUploadResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description: java类作用描述
 * @Author: lzp
 * @CreateDate: 2023/6/19 15:27
 * @UpdateRemark: 更新说明
 */
public class UploadPictureUtil {


    private static UploadCallBack callBack;

    public static void uploadPic(String bucket, String type, String imgPathSel, String isIm, UploadCallBack mCallBack) {
        getPresignedUrl(bucket, type, imgPathSel, isIm);
        callBack = mCallBack;
    }

    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    public static void getPresignedUrl(String bucket, String type, String imgPathSel, String isIm) {
        // bucket:  1-病历 2-评论(反馈) 3-头像 4-轮播图 5-用户资源 6-图标 7-封面 8-其他 9-视频
        RestProxy.getInstance().getPresignedUrl(bucket, new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseStringResponse baseStringResponse) {
                try {
                    String data = baseStringResponse.data;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        String resourceId = substring.substring(substring.lastIndexOf("/") + 1);
                        Log.e("presignedUrl -----", resourceId);
                        JDConstant.SUBMIT_MINIO = baseStringResponse.data;
                        uploadFileMinio(bucket, type, imgPathSel, resourceId, isIm, baseStringResponse.data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable e) {
                callBack.fail(e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private static void uploadFileMinio(String bucket, String type, String imgPath, String resourceId, String isIm, String hostUrl) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), r -> {
            AtomicInteger threadNum = new AtomicInteger(1);
            Thread t = new Thread(r);
            String name = "UploadImage_Thread-" + threadNum.getAndIncrement();
            t.setName(name);
            t.setPriority(Thread.NORM_PRIORITY);
            return t;
        });
        threadPoolExecutor.execute(() -> {
            try {
                Log.e("TAG-路径-----", imgPath);
                File file = new File(imgPath);
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e("字节数---", available + "");
                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse("image/png");//设置类型
                RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url(hostUrl)
                        .put(requestBody)
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("TAG-失败：", e.toString() + "");
                        callBack.fail(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        assert response.body() != null;
                        String string = response.body().toString();
                        Log.e("minio成功---", string + "");
                        uploadFileTb(bucket, type, resourceId, available + "", isIm);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("上传文件失败：", e.getMessage());
            }
        });
        threadPoolExecutor.shutdown();
    }


    /**
     * 上传照片到服务器数据库
     *
     * @time 2020/12/2 9:55
     */
    private static void uploadFileTb(String bucket, String type, String resourceId, String available, String isIm) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ', 81-护理图片
        RestProxy.getInstance().uploadFileTb(bucket, type, resourceId, BaseApplication.doctorId, available, isIm, new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                callBack.success(picUploadResponse.data);
            }

            @Override
            public void onError(Throwable e) {
                callBack.fail(e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public interface UploadCallBack {
        void success(PicUploadResponse.ImageBean imageBean);

        void fail(Throwable e);
    }
}
